<template>
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="销售门店" prop="tenantIds">
            <el-select
              v-model="queryParams.tenantIds"
              placeholder="请选择销售门店"
              clearable
              multiple
            >
              <el-option
                v-for="dict in tenantList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="选择日期" prop="createTime">
            <el-date-picker
              v-model="queryParams.times"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              :shortcuts="defaultShortcuts"
              :disabled-date="disabledDate"
              end-placeholder="结束日期"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item prop="query">
            <el-radio-group
              v-model="queryParams.query"
              @change="
                () => {
                  queryParams.times = []
                  handleQuery()
                }
              "
            >
              <el-radio-button :value="0">今日</el-radio-button>
              <el-radio-button :value="1">本周</el-radio-button>
              <el-radio-button :value="2">本月</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon class="mr-5px" icon="ep:search" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon class="mr-5px" icon="ep:refresh" />
              重置
            </el-button>
            <el-button :loading="exportLoading" plain type="success" @click="handleExport">
              <Icon class="mr-5px" icon="ep:download" />
              导出
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>
  <!-- 统计卡片 -->
  <el-row :gutter="10">
    <el-col :xl="6" :lg="8" :md="8" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="总实收/店均实收"
        class="mb-10px"
        icon="streamline:money-cash-file-dollar-common-money-currency-cash-file"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        scene="1"
        :value="`${fenToYuan(summary?.otherPrice || 0)}/${fenToYuan(summary?.otherPriceAvg || 0)}`"
      />
    </el-col>
    <el-col :xl="6" :lg="8" :md="8" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="总销售/店均销售"
        class="mb-10px"
        icon="streamline:money-cash-file-dollar-common-money-currency-cash-file"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        scene="1"
        :value="`${fenToYuan(summary?.totalPrice || 0)}/${fenToYuan(summary?.totalPriceAvg || 0)}`"
      />
    </el-col>
    <el-col :xl="6" :lg="8" :md="8" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="总还款/店均还款"
        class="mb-10px"
        icon="streamline:money-cash-file-dollar-common-money-currency-cash-file"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        scene="1"
        :value="`${fenToYuan(summary?.repayPrice || 0)}/${fenToYuan(summary?.repayPriceAvg || 0)}`"
      />
    </el-col>
    <el-col :xl="6" :lg="8" :md="8" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="总充值/店均充值"
        class="mb-10px"
        icon="streamline:money-cash-file-dollar-common-money-currency-cash-file"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        scene="1"
        :value="`${fenToYuan(summary?.rechargePrice || 0)}/${fenToYuan(summary?.rechargePriceAvg || 0)}`"
      />
    </el-col>
    <el-col :xl="6" :lg="8" :md="8" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="总欠款/店均欠款"
        class="mb-10px"
        icon="mdi:cash-plus"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        scene="1"
        :value="`${fenToYuan(summary?.arrearsPrice || 0)}/${fenToYuan(summary?.arrearsPriceAvg || 0)}`"
      />
    </el-col>
    <el-col :xl="6" :lg="8" :md="8" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="总划卡/店均划卡"
        class="mb-10px"
        icon="mdi:cash-plus"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        scene="1"
        :value="`${fenToYuan(summary?.ppcPrice || 0)}/${fenToYuan(summary?.ppcPriceAvg || 0)}`"
      />
    </el-col>
    <el-col :xl="6" :lg="8" :md="8" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="总消耗/店均消耗"
        class="mb-10px"
        icon="mdi:cash-sync"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        scene="1"
        :value="`${fenToYuan(summary?.performancePrice || 0)}/${fenToYuan(summary?.performancePriceAvg || 0)}`"
      />
    </el-col>
    <el-col :xl="6" :lg="8" :md="8" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="总盈亏/率"
        class="mb-10px"
        icon="icon-park-outline:transaction-order"
        icon-color="bg-blue-100"
        icon-bg-color="text-blue-500"
        :decimals="0"
        scene="1"
        prefix="￥"
        :value="`${fenToYuan(summary?.plossPrice || 0)}/${summary?.plossPriceAvg}%`"
      />
    </el-col>
  </el-row>
  <!-- 列表 -->
  <ContentWrap>
    <PureTableBar title="" :columns="columns" @refresh="handleQuery">
      <template #default="{ size, dynamicColumns }">
        <pure-table
          ref="tableRef"
          row-key="id"
          @selection-change="handleSelectionChange"
          align-whole="center"
          :loading="loading"
          :size="size"
          :data="list"
          :columns="dynamicColumns"
          :default-sort="{ prop: 'otherPrice', order: 'descending' }"
        >
          <template #tenantName="scope">
            <div class="flex">
              <el-image
                :preview-teleported="true"
                :src="scope.row.picUrl"
                class="w-[48px] h-[48px] m-r-10px rounded-4px align-middle"
              />
              <el-text>{{ scope.row.nodeName }}</el-text>
            </div>
          </template>
          <template #otherPrice="scope">
            <el-text :type="scope.row.otherPrice < summary?.otherPriceAvg ? 'success' : ''"
              >{{ fenToYuan(scope.row.otherPrice) }}元</el-text
            >
          </template>
          <template #totalPrice="scope">
            <el-text :type="scope.row.totalPrice < summary?.totalPriceAvg ? 'success' : ''"
              >{{ fenToYuan(scope.row.totalPrice) }}元</el-text
            >
          </template>
          <template #repayPrice="scope">
            <el-text :type="scope.row.repayPrice < summary?.repayPriceAvg ? 'success' : ''"
              >{{ fenToYuan(scope.row.repayPrice) }}元</el-text
            >
          </template>
          <template #rechargePrice="scope">
            <el-text :type="scope.row.rechargePrice < summary?.rechargePriceAvg ? 'success' : ''"
              >{{ fenToYuan(scope.row.rechargePrice) }}元</el-text
            >
          </template>

          <template #ppcPrice="scope">
            <el-text :type="scope.row.ppcPrice < summary?.ppcPriceAvg ? 'success' : ''"
              >{{ fenToYuan(scope.row.ppcPrice) }}元</el-text
            >
          </template>
          <template #performancePrice="scope">
            <el-text
              :type="scope.row.performancePrice < summary?.performancePriceAvg ? 'success' : ''"
              >{{ fenToYuan(scope.row.performancePrice) }}元</el-text
            >
          </template>
          <template #operation="scope">
            <div class="flex items-center justify-center">
              <el-button link type="primary" @click="openDetail(scope.row.tenantId)"
                >详情</el-button
              >
              <el-button
                link
                type="primary"
                :loading="exportLoading"
                @click="handleExport(scope.row)"
                >导出</el-button
              >
            </div>
          </template>
          <template #empty>
            <Empty />
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <!-- 分页 -->
  </ContentWrap>
</template>
<script lang="ts" setup>
import * as StatisticsApi from '@/api/statistics/tenant/index'
import { PureTableBar } from '@/components/RePureTableBar'
import * as ShopUserApi from '@/api/shop/system/user/index'
import { defaultShortcuts } from '@/utils/formatTime'
import SummaryCard from '@/components/SummaryCard/index.vue'
import { fenToYuan } from '@/utils'

const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
defineOptions({ name: 'MemberUser' })
const message = useMessage() // 消息弹窗
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据

const queryParams = reactive({
  query: 0 as any,
  times: [] as any,
  tenantIds: [] as any
})
const queryFormRef = ref() // 搜索的表单
const selectedIds = ref<number[]>([]) // 表格的选中 ID 数组
const tableRef = ref()
import * as TradeOrderApi from '@/api/mall/trade/order'

const summary = ref<any>() // 订单统计数据

import { useUser } from './utils/hook'
const { columns } = useUser()
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 统计

    const data = await StatisticsApi.getStatisticsRebateTenant(queryParams)
    summary.value = data.total
    list.value = data.data
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetprops()
  handleQuery()
}
/** 导出按钮操作 */
const exportLoading = ref(false) // 导出的加载中
import download from '@/utils/download'

const handleExport = async (row: any) => {
  let xlsName = '门店业绩.xls'
  if (row.tenantId) {
    queryParams.tenantIds = [row.tenantId]
    xlsName = row.nodeName + '门店业绩.xls'
  }

  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await StatisticsApi.exportRebate(queryParams)
    download.excel(data, xlsName)
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 打开会员详情 */
const { push } = useRouter()
const openDetail = (id: number) => {
  push({ name: 'MemberUserDetail', params: { id } })
}

/** 表格选中事件 */
const handleSelectionChange = (rows: any[]) => {
  console.log(rows)
  selectedIds.value = rows.map((row) => row.id)
}

/** 门店精简列表 */
import * as TenantApi from '@/api/system/tenant'
const tenantList = ref<any[]>([])
const getTenantList = async () => {
  let params = {
    tenantType: 4
  }
  const data = await TenantApi.getTenantPage(params)

  data.list.map((ele) => {
    tenantList.value.push({
      name: ele.name,
      id: ele.id
    })
  })
}

onMounted(async () => {
  getList()
  getTenantList()
})
</script>
